package com.atguigu.gmall.common.rabbit.util;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.rabbit.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author: atguigu
 * @create: 2023-06-26 14:51
 */
@Component
public class RabbitService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 发送消息到MQ服务器工具方法
     *
     * @param exchange   交换机
     * @param routingKey 路由键
     * @param obj        业务数据
     * @return
     */
    public boolean sendMessage(String exchange, String routingKey, Object obj) {
        //1.封装相关数据对象
        GmallCorrelationData correlationData = new GmallCorrelationData();
        String id = UUID.randomUUID().toString().replace("-", "");
        correlationData.setId(id);
        correlationData.setMessage(obj);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        //2.将相关数据存入Redis
        String key = "mq:" + id;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(correlationData), 5, TimeUnit.MINUTES);
        //3.调用发送消息方法到MQ
        rabbitTemplate.convertAndSend(exchange, routingKey, obj, correlationData);
        return true;
    }


    /**
     * 延迟消息发送
     *
     * @param exchange
     * @param routingKey
     * @param obj
     * @param delayTime  延迟时间单位:s
     * @return
     */
    public boolean sendDelayMessage(String exchange, String routingKey, Object obj, Integer delayTime) {
        GmallCorrelationData correlationData = new GmallCorrelationData();
        String id = UUID.randomUUID().toString().replace("-", "");
        correlationData.setId(id);
        correlationData.setMessage(obj);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setDelay(true);
        correlationData.setDelayTime(delayTime);
        //2.将相关数据存入Redis
        String key = "mq:" + id;
        redisTemplate.opsForValue().set(key, JSON.toJSONString(correlationData), 5, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange, routingKey, obj, (message) -> {
            message.getMessageProperties().setDelay(delayTime * 1000);
            return message;
        }, correlationData);
        return true;
    }

}
